package com.example.weight.greenSeasons.compost;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class DuifeiWeekMaintenanceActivity extends AppCompatActivity {

    private String name, role, factory;
    
    private TextView planDate;

    private CheckBox fandaoji, dundaixitong, fuliaoshusongxitong, hunliaojiaobanluoxuan,
            hunliaoshusongluoxuan, niliaoshusongluoxuan, duifeichejianbaoqixitong, duifeichejianchuchoufengji,
            fdjCheck, ddxtCheck, flssxtCheck, hljblxCheck, hlsslxCheck, nlsslxCheck, dfcjbqxtCheck, dfcjccfjCheck;

    private EditText fdjText, ddxtText, flssxtText, hljblxText, hlsslxText, nlsslxText, dfcjbqxtText, dfcjccfjText;

    private Map<String, String> fromIdMap;

    private RequestQueue queue;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duifei_week_maintenance);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar=findViewById(R.id.duifeiWeek_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }
            @Override
            public void onTitleClick(View v) {}
            @Override
            public void onRightClick(View v) {}
        });

        TextView actualDate = findViewById(R.id.duifeiWeek_date);
        String tempText = actualDate.getText().toString();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        actualDate.setText(tempText+year+"年"+month+"月"+day+"日");

        fandaoji = findViewById(R.id.duifeiWeek_fandaoji);
        dundaixitong = findViewById(R.id.duifeiWeek_dundaixitong);
        fuliaoshusongxitong = findViewById(R.id.duifeiWeek_fuliaoshusongxitong);
        hunliaojiaobanluoxuan = findViewById(R.id.duifeiWeek_hunliaojiaobanluoxuan);
        hunliaoshusongluoxuan = findViewById(R.id.duifeiWeek_hunliaoshusongluoxuan);
        niliaoshusongluoxuan = findViewById(R.id.duifeiWeek_niliaoshusongluoxuan);
        duifeichejianbaoqixitong = findViewById(R.id.duifeiWeek_duifeichejianbaoqixitong);
        duifeichejianchuchoufengji = findViewById(R.id.duifeiWeek_duifeichejianchuchoufengji);
        fdjCheck = findViewById(R.id.duifeiWeek_fandaoji_check);
        ddxtCheck = findViewById(R.id.duifeiWeek_dundaixitong_check);
        flssxtCheck = findViewById(R.id.duifeiWeek_fuliaoshusongxitong_check);
        hljblxCheck = findViewById(R.id.duifeiWeek_hunliaojiaobanluoxuan_check);
        hlsslxCheck = findViewById(R.id.duifeiWeek_hunliaoshusongluoxuan_check);
        nlsslxCheck = findViewById(R.id.duifeiWeek_niliaoshusongluoxuan_check);
        dfcjbqxtCheck = findViewById(R.id.duifeiWeek_duifeichejianbaoqixitong_check);
        dfcjccfjCheck = findViewById(R.id.duifeiWeek_duifeichejianchuchoufengji_check);
        fdjText = findViewById(R.id.duifeiWeek_fdj_text);
        ddxtText = findViewById(R.id.duifeiWeek_ddxt_text);
        flssxtText = findViewById(R.id.duifeiWeek_flssxt_text);
        hljblxText = findViewById(R.id.duifeiWeek_hljblx_text);
        hlsslxText = findViewById(R.id.duifeiWeek_hlsslx_text);
        nlsslxText = findViewById(R.id.duifeiWeek_nlsslx_text);
        dfcjbqxtText = findViewById(R.id.duifeiWeek_dfcjbqxt_text);
        dfcjccfjText = findViewById(R.id.duifeiWeek_dfcjccfj_text);

        fromIdMap = new HashMap<>();

        queue = Volley.newRequestQueue(this);

        setCheckStatus(fandaoji, fdjCheck);
        setCheckStatus(dundaixitong, ddxtCheck);
        setCheckStatus(fuliaoshusongxitong, flssxtCheck);
        setCheckStatus(hunliaojiaobanluoxuan, hljblxCheck);
        setCheckStatus(hunliaoshusongluoxuan, hlsslxCheck);
        setCheckStatus(niliaoshusongluoxuan, nlsslxCheck);
        setCheckStatus(duifeichejianbaoqixitong, dfcjbqxtCheck);
        setCheckStatus(duifeichejianchuchoufengji, dfcjccfjCheck);
        if (role.equals("操作人")) {
            fdjCheck.setEnabled(false);
            ddxtCheck.setEnabled(false);
            flssxtCheck.setEnabled(false);
            hljblxCheck.setEnabled(false);
            hlsslxCheck.setEnabled(false);
            nlsslxCheck.setEnabled(false);
            dfcjbqxtCheck.setEnabled(false);
            dfcjccfjCheck.setEnabled(false);
        }

        // 操作人填表
        fandaoji.setOnClickListener(v -> {
            if (fandaoji.isChecked()) {
                operatorAddForm(fandaoji, fdjText.getText().toString());
            }
        });
        dundaixitong.setOnClickListener(v -> {
            if (dundaixitong.isChecked()) {
                operatorAddForm(dundaixitong, ddxtText.getText().toString());
            }
        });
        fuliaoshusongxitong.setOnClickListener(v -> {
            if (fuliaoshusongxitong.isChecked()){
                operatorAddForm(fuliaoshusongxitong, flssxtText.getText().toString());
            }
        });
        hunliaojiaobanluoxuan.setOnClickListener(v -> {
            if (hunliaojiaobanluoxuan.isChecked()) {
                operatorAddForm(hunliaojiaobanluoxuan, hljblxText.getText().toString());
            }
        });
        hunliaoshusongluoxuan.setOnClickListener(v -> {
            if (hunliaoshusongluoxuan.isChecked()) {
                operatorAddForm(hunliaoshusongluoxuan, hlsslxText.getText().toString());
            }
        });
        niliaoshusongluoxuan.setOnClickListener(v -> {
            if (niliaoshusongluoxuan.isChecked()) {
                operatorAddForm(niliaoshusongluoxuan, nlsslxText.getText().toString());
            }
        });
        duifeichejianbaoqixitong.setOnClickListener(v -> {
            if (duifeichejianbaoqixitong.isChecked()){
                operatorAddForm(duifeichejianbaoqixitong, dfcjbqxtText.getText().toString());
            }
        });
        duifeichejianchuchoufengji.setOnClickListener(v -> {
            if (duifeichejianchuchoufengji.isChecked()) {
                operatorAddForm(duifeichejianchuchoufengji, dfcjccfjText.getText().toString());
            }
        });

        // 检查人填表
        fdjCheck.setOnClickListener(v -> {
            if (fdjCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(fandaoji.getText().toString())) != null)
                    examinerAddForm(fromId, fdjText.getText().toString(), fdjCheck);
            }
        });
        ddxtCheck.setOnClickListener(v -> {
            if (ddxtCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(dundaixitong.getText().toString())) != null)
                    examinerAddForm(fromId, ddxtText.getText().toString(), ddxtCheck);
            }
        });
        flssxtCheck.setOnClickListener(v -> {
            if (flssxtCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(fuliaoshusongxitong.getText().toString())) != null)
                    examinerAddForm(fromId, flssxtText.getText().toString(), flssxtCheck);
            }
        });
        hljblxCheck.setOnClickListener(v -> {
            if (hljblxCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(hunliaojiaobanluoxuan.getText().toString())) != null)
                    examinerAddForm(fromId, hljblxText.getText().toString(), hljblxCheck);
            }
        });
        hlsslxCheck.setOnClickListener(v -> {
            if (hlsslxCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(hunliaoshusongluoxuan.getText().toString())) != null)
                    examinerAddForm(fromId, hlsslxText.getText().toString(), hlsslxCheck);
            }
        });
        nlsslxCheck.setOnClickListener(v -> {
            if (nlsslxCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(niliaoshusongluoxuan.getText().toString())) != null)
                    examinerAddForm(fromId, nlsslxText.getText().toString(), nlsslxCheck);
            }
        });
        dfcjbqxtCheck.setOnClickListener(v -> {
            if (dfcjbqxtCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(duifeichejianbaoqixitong.getText().toString())) != null)
                    examinerAddForm(fromId, dfcjbqxtText.getText().toString(), dfcjbqxtCheck);
            }
        });
        dfcjccfjCheck.setOnClickListener(v -> {
            if (dfcjccfjCheck.isChecked()) {
                String fromId;
                if ((fromId = fromIdMap.get(duifeichejianchuchoufengji.getText().toString())) != null)
                    examinerAddForm(fromId, dfcjccfjText.getText().toString(), dfcjccfjCheck);
            }
        });
    }

    private void operatorAddForm(CheckBox checkBox, String comment) {
        String[] temp = checkBox.getText().toString().split("[ \n]");
        String fName = temp[0];
        String maintainContent = temp[1];
        new AlertDialog.Builder(this)
                .setTitle("确定提交吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> checkBox.setChecked(false)))
                .setPositiveButton("确定", (dialog, which) -> {
                    checkBox.setEnabled(false);
                    checkBox.setTextColor(Color.GREEN);
                    String url = Config.url + "/shlj/sjqCompostProduceMaintenance/add_week_recorder";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(DuifeiWeekMaintenanceActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(DuifeiWeekMaintenanceActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(DuifeiWeekMaintenanceActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", fName);
                            map.put("maintenanceContent", maintainContent);
                            map.put("isNormal", comment.equals("")?"1":"0");
                            map.put("remarks", comment);
                            map.put("operator", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }).show();
    }

    private void setCheckStatus(CheckBox operatorCB, CheckBox examinerCB) {
        String operatorCBText = operatorCB.getText().toString();
        String[] temp = operatorCBText.split("[ \n]");
        String fName = temp[0];
        String maintainContent = temp[1];
        String url = Config.url + "/shlj/sjqCompostProduceMaintenance/getlast_week";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                operatorCB.setChecked(true);
                                operatorCB.setEnabled(false);
                                operatorCB.setTextColor(Color.GREEN);
                                setRemarks(operatorCB, data.getString("remarks"));

//                                String examiner = data.getString("examiner");
                                if (!data.isNull("inspector") && !data.getString("inspector").equals("") && data.getString("factory").equals(factory)) {
                                    // 检查人已检查某项，该项不可再检查
                                    examinerCB.setChecked(true);
                                    examinerCB.setEnabled(false);
                                    examinerCB.setTextColor(Color.GREEN);
                                } else {
                                    // 若存在检查人未检查项，将其添加到formIdList中
                                    fromIdMap.put(operatorCBText, data.getString("id"));
                                }
                            } else {
                                if (role.equals("检查人")) {
                                    // 如果操作人未保养，检查人不可检查
                                    operatorCB.setEnabled(false);
                                    examinerCB.setEnabled(false);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DuifeiWeekMaintenanceActivity.this,
                        "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("equipment_name", fName);
                map.put("maintenanceContent", maintainContent);
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    private void examinerAddForm(String formId, String comment, CheckBox checkBox) {
        new AlertDialog.Builder(this)
                .setTitle("确定检查吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) -> checkBox.setChecked(false)))
                .setPositiveButton("确定", (dialog, which) -> {
                    checkBox.setEnabled(false);
                    checkBox.setTextColor(Color.GREEN);
                    String url = Config.url + "/shlj/sjqCompostProduceMaintenance/add_week_inspector";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(DuifeiWeekMaintenanceActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(DuifeiWeekMaintenanceActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(DuifeiWeekMaintenanceActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", formId);
                            map.put("Inspector", name);
                            map.put("remarks", comment);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                }).show();
    }

    private void setRemarks(CheckBox checkBox, String remarks) {
        switch (checkBox.getText().toString()) {
            case "1#吨袋系统 清理灰尘链条刷油":
                fdjText.setText(remarks);
                break;
            case "2#-4#吨袋系统 清理灰尘链条刷油":
                ddxtText.setText(remarks);
                break;
            case "辅料输送系统 轴承加注润滑油":
                flssxtText.setText(remarks);
                break;
            case "混料搅拌螺旋 轴承加注润滑油":
                hljblxText.setText(remarks);
                break;
            case "混料输送螺旋 轴承加注润滑油":
                hlsslxText.setText(remarks);
                break;
            case "泥料输送螺旋 轴承加注润滑油":
                nlsslxText.setText(remarks);
                break;
            case "堆肥车间曝气系统\n测量电流值，检查电源端子":
                dfcjbqxtText.setText(remarks);
                break;
            case "堆肥车间除臭风机\n测量电流值，检查电源端子":
                dfcjccfjText.setText(remarks);
                break;
            default:
        }
    }
}